package com.app.biz.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.app.biz.domain.OperationEconomic;
import com.app.biz.domain.request.BizIndustrialValueAddedByCityRequest;
import com.app.biz.excel.entity.BizIndustrialValueAddedByCityExcelEntity;
import com.app.biz.mapper.BizIndustrialValueAddedByCityFormalMapper;
import com.app.biz.mapper.OperationEconomicMapper;
import com.app.biz.service.IOperationService;
import com.app.common.core.domain.AjaxResult;
import com.app.common.utils.DateUtils;
import com.app.common.utils.DictUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.biz.mapper.BizIndustrialValueAddedByCityMapper;
import com.app.biz.domain.BizIndustrialValueAddedByCity;
import com.app.biz.service.IBizIndustrialValueAddedByCityService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 分市工业增加值Service业务层处理
 *
 * @author SangGuangCan
 * @date 2023-12-27
 */
@Service
public class BizIndustrialValueAddedByCityServiceImpl implements IBizIndustrialValueAddedByCityService
{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final BizIndustrialValueAddedByCityMapper bizIndustrialValueAddedByCityMapper;

    private final BizIndustrialValueAddedByCityFormalMapper batchInsertBizIndustrialSectorMetricsFormalMapper;

    @Autowired
    private IOperationService operationService;

    @Autowired
    public BizIndustrialValueAddedByCityServiceImpl(BizIndustrialValueAddedByCityMapper bizIndustrialValueAddedByCityMapper,
                                                    BizIndustrialValueAddedByCityFormalMapper batchInsertBizIndustrialSectorMetricsFormalMapper){
        this.bizIndustrialValueAddedByCityMapper = bizIndustrialValueAddedByCityMapper;
        this.batchInsertBizIndustrialSectorMetricsFormalMapper = batchInsertBizIndustrialSectorMetricsFormalMapper;
    }

    /**
     * 查询分市工业增加值
     *
     * @param baseId 分市工业增加值主键
     * @return 分市工业增加值
     */
    @Override
    public BizIndustrialValueAddedByCity selectBizIndustrialValueAddedByCityByBaseId(String baseId)
    {
        return bizIndustrialValueAddedByCityMapper.selectBizIndustrialValueAddedByCityByBaseId(baseId);
    }

    /**
     * 查询分市工业增加值列表
     *
     * @param bizIndustrialValueAddedByCity 分市工业增加值
     * @return 分市工业增加值
     */
    @Override
    public List<BizIndustrialValueAddedByCity> selectBizIndustrialValueAddedByCityList(BizIndustrialValueAddedByCity bizIndustrialValueAddedByCity)
    {
        return bizIndustrialValueAddedByCityMapper.selectBizIndustrialValueAddedByCityList(bizIndustrialValueAddedByCity);
    }

    /**
     * 新增分市工业增加值
     *
     * @param bizIndustrialValueAddedByCity 分市工业增加值
     * @return 结果
     */
    @Override
    public int insertBizIndustrialValueAddedByCity(BizIndustrialValueAddedByCity bizIndustrialValueAddedByCity)
    {
        bizIndustrialValueAddedByCity.setBaseId(IdUtil.simpleUUID());
        bizIndustrialValueAddedByCity.setBaseCrateTime(DateUtils.getNowDate());
        return bizIndustrialValueAddedByCityMapper.insertBizIndustrialValueAddedByCity(bizIndustrialValueAddedByCity);
    }

    /**
     * 修改分市工业增加值
     *
     * @param bizIndustrialValueAddedByCity 分市工业增加值
     * @return 结果
     */
    @Override
    public int updateBizIndustrialValueAddedByCity(BizIndustrialValueAddedByCity bizIndustrialValueAddedByCity)
    {
        return bizIndustrialValueAddedByCityMapper.updateBizIndustrialValueAddedByCity(bizIndustrialValueAddedByCity);
    }

    /**
     * <p>
     * 查询数据库中数据的日期(year_month字段)并进行去重复操作<br/>
     * 主要用于的是APP端左上角的日期过滤
     * </p>
     *
     * @return 日期的数组
     */
    @Override
    public List<String> getUniqueDatesFromDatabase() {
        List<String> uniqueDatesFromDatabase = bizIndustrialValueAddedByCityMapper.getUniqueDatesFromDatabase();
        if(!uniqueDatesFromDatabase.isEmpty()){
            //Mysql中去重关键字和排序不能对同一字段同时使用，这里通过代码来去重
            return uniqueDatesFromDatabase.stream().distinct().collect(Collectors.toList());
        }
        return uniqueDatesFromDatabase;
    }

    /**
     * 批量删除分市工业增加值
     *
     * @param baseIds 需要删除的分市工业增加值主键
     * @return 结果
     */
    @Override
    public int deleteBizIndustrialValueAddedByCityByBaseIds(String[] baseIds)
    {
        return bizIndustrialValueAddedByCityMapper.deleteBizIndustrialValueAddedByCityByBaseIds(baseIds);
    }

    /**
     * 删除分市工业增加值信息
     *
     * @param baseId 分市工业增加值主键
     * @return 结果
     */
    @Override
    public int deleteBizIndustrialValueAddedByCityByBaseId(String baseId)
    {
        return bizIndustrialValueAddedByCityMapper.deleteBizIndustrialValueAddedByCityByBaseId(baseId);
    }

    /**
     * 查询分市工业增加值列表
     *
     * @param request
     * @return
     */
    @Override
    public List<BizIndustrialValueAddedByCity> getIndustrialValueAddedByCityList(BizIndustrialValueAddedByCityRequest request) {
        String specifiedStr = request.getDates();
        DateTime specifiedDate = DateUtil.parse(specifiedStr, "yyyy年MM月");
        request.setDates(DateUtil.format(specifiedDate,"yyyy-MM-dd"));
        List<BizIndustrialValueAddedByCity> result = bizIndustrialValueAddedByCityMapper.getIndustrialValueAddedByCityList(request);
        return result;
    }

    /**
     * @return
     */
    @Override
    public boolean transferDataInOneClick() {
        try{
            /* 查询数据库中最新的一条日期 */
//            String latestDateStr = bizIndustrialValueAddedByCityMapper.getLatestDateData();
//            BizIndustrialValueAddedByCity params = new BizIndustrialValueAddedByCity();
//            params.setYearMonth(DateUtils.parseDate(latestDateStr,"yyyy-MM-dd"));

            List<BizIndustrialValueAddedByCity> result = bizIndustrialValueAddedByCityMapper.selectBizIndustrialValueAddedByCityAllData();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM");
            int count = 0;
            List<BizIndustrialValueAddedByCity> list = new ArrayList<>();
            for(BizIndustrialValueAddedByCity item : result){
                item.setBaseCrateTime(DateUtils.getNowDate());
                list.add(item);
                count++;
                if(count >= 100){
                    batchInsertBizIndustrialSectorMetricsFormalMapper.batchInsertBizIndustrialSectorMetricsFormal(list);
                    List<OperationEconomic> olist=list.stream().map(items->{
                        OperationEconomic operationEconomic=new OperationEconomic();
                        operationEconomic.setBaseId(items.getBaseId());
                        operationEconomic.setRegion(items.getRegion());
                        operationEconomic.setYearMonth(simpleDateFormat.format(items.getYearMonth()));
                        operationEconomic.setMonthlyGrowthRate(items.getMonthlyGrowthRate());
                        operationEconomic.setCumulativeGrowthRate(items.getCumulativeGrowthRate());
                        operationEconomic.setBaseCrateTime(new Date());
                        return  operationEconomic;
                    }).collect(Collectors.toList());
                    operationService.batchInsertOperationEconomic(olist);
                    list.clear();
                    olist.clear();
                }
            }

            if(!list.isEmpty()){
                batchInsertBizIndustrialSectorMetricsFormalMapper.batchInsertBizIndustrialSectorMetricsFormal(list);
                List<OperationEconomic> olist=list.stream().map(items->{
                    OperationEconomic operationEconomic=new OperationEconomic();
                    operationEconomic.setBaseId(items.getBaseId());
                    operationEconomic.setRegion(items.getRegion());
                    operationEconomic.setYearMonth(simpleDateFormat.format(items.getYearMonth()));
                    operationEconomic.setMonthlyGrowthRate(items.getMonthlyGrowthRate());
                    operationEconomic.setCumulativeGrowthRate(items.getCumulativeGrowthRate());
                    operationEconomic.setBaseCrateTime(new Date());
                    return  operationEconomic;
                }).collect(Collectors.toList());
                operationService.batchInsertOperationEconomic(olist);
                list.clear();
                olist.clear();
            }
            return true;
        }catch (Exception e){
            logger.error("未知错误:{}",e.getMessage());
            return false;
        }
    }

    /**
     *
     */
    @Override
    public void clearAllTableData() {
        bizIndustrialValueAddedByCityMapper.clearAllTableData();
    }

    /**
     * <p>
     * 导入分市工业增加值数据
     * </p>
     *
     * @param absoluteExcelPath 上传的Excel文件
     * @param yearMonth         月份
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importExcel(String absoluteExcelPath, String yearMonth) {
        List<BizIndustrialValueAddedByCityExcelEntity> excelDataArgs = EasyExcel.read(absoluteExcelPath).head(BizIndustrialValueAddedByCityExcelEntity.class).headRowNumber(3).sheet().doReadSync();
        try{
            if(excelDataArgs.isEmpty()){
                logger.warn("分市工业增加值数据");
                return AjaxResult.warn("没有读取到分市工业增加值数据");
            }else{
                List<BizIndustrialValueAddedByCity> list = new ArrayList<>();
                for(BizIndustrialValueAddedByCityExcelEntity item : excelDataArgs){
                    BizIndustrialValueAddedByCity bizIndustrialValueAddedByCity = new BizIndustrialValueAddedByCity();
                    bizIndustrialValueAddedByCity.setBaseId(IdUtil.simpleUUID());
                    bizIndustrialValueAddedByCity.setBaseCrateTime(DateUtils.getNowDate());
                    bizIndustrialValueAddedByCity.setYearMonth(DateUtils.parseDate(yearMonth,"yyyy-MM"));
                    BeanUtil.copyProperties(item,bizIndustrialValueAddedByCity);
                    String regionCode = DictUtils.getDictValue("administrative_region", item.getRegion());
                    bizIndustrialValueAddedByCity.setRegion(regionCode);
                    list.add(bizIndustrialValueAddedByCity);
                }
                if(list.isEmpty()){
                    logger.warn("过滤后没有符合要求的数据！");
                }else{
                    bizIndustrialValueAddedByCityMapper.batchInsertBizIndustrialValueAddedByCity(list);
                }
                return AjaxResult.success();
            }
        }catch (Exception e){
            logger.error("导入分市工业增加值数据时出现异常,执行回滚");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.warn("导入分市工业增加值数据时出现异常");
        }
    }

    /**
     * @return
     */
    @Override
    public List<BizIndustrialValueAddedByCity> selectBizIndustrialValueAddedByCityListNoParams() {
        return bizIndustrialValueAddedByCityMapper.selectBizIndustrialValueAddedByCityListNoParams();
    }
}
